package com.atzzy.ysmall.ysmall_api.PayController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atzzy.ysmall.ysmall_allService.orderService.OrderService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author JAVAZeng
 * @Date 2022/4/7 16:16
 * @Version 1.0
 */
@RestController
@RequestMapping("pay")
@CrossOrigin
public class PayController {

    @Reference
    private OrderService orderService;

    //支付回调接口
    @PostMapping("callBackSuc")
    public String success(HttpServletRequest request) throws Exception {
        System.out.println("-------------callback");
        ServletInputStream inputStream = request.getInputStream();
        byte[] bs = new byte[1024];
        int len = -1;
        StringBuilder builder = new StringBuilder();
        while((len = inputStream.read(bs))!=-1){
            builder.append(new String(bs,0,len));
        }
        String s = builder.toString();

        Map<String,String> map = WXPayUtil.xmlToMap(s);

        if(map!=null && "success".equalsIgnoreCase(map.get("result_code"))){
            //支付成功
            //修改订单状态为 “待发货/已支付”
            //响应微信平台
            String orderId = map.get("out_trade_no");
            int i = orderService.updateOrderStatus(orderId, "2");
            if(i>0){
                HashMap<String,String> resp = new HashMap<String, String>();
                resp.put("return_code","success");
                resp.put("return_msg","OK");
                resp.put("appid",map.get("appid"));
                resp.put("result_code","success");
//                System.out.println(resp);
                System.out.println("支付成功-------------------------");
                return WXPayUtil.mapToXml(resp);
            }
        }
        return null;
    }
}
